package io.modifier.basic.compose.animation

import androidx.compose.animation.core.*
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import io.modifier.basic.compose.theme.themeAdapter


/**
 * @param play 是否播放动画
 */
@Composable
fun AudioPlayAnim(
    play: Boolean = true,
    heightDp: Float = 22f,
    defaultColor: Color = Color(0x4D0487FF).themeAdapter(),
    color: Color = Color(0xFF0487FF).themeAdapter(),
) {

    val onePartHeightDp = remember { heightDp / 22 }
    val percentList = remember { listOf(8, 14, 8, 11, 22, 11, 6) }

    var currentIndex: State<Float> = remember { mutableStateOf(-1f) }

    if (play) {
        val infiniteTransition = rememberInfiniteTransition(label = "")
        currentIndex = infiniteTransition.animateFloat(
            initialValue = -1f, targetValue = percentList.size.toFloat() + 2,
            animationSpec = infiniteRepeatable(
                animation = tween(1500, easing = LinearEasing),
                repeatMode = RepeatMode.Restart,
            ),
            label = "",
        )
    }

    Row(
        Modifier.height(22.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.Center,
    ) {

        percentList.forEachIndexed { index, percent ->
            val finalHeight = percent * onePartHeightDp

            Box(
                modifier = Modifier
                    .padding(horizontal = 1.5.dp)
                    .width(3.dp)
                    .height(finalHeight.dp)
                    .clip(RoundedCornerShape(1.5.dp))
                    .background(
                        if (currentIndex.value.toInt() >= index + 1) color else defaultColor,
                    ),
            )
        }

    }
}


@Preview(showBackground = true, backgroundColor = 0xffffffff)
@Composable
fun RenderAudioPlayAnimPreView() {
    AudioPlayAnim()
}
